﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using System.Threading.Tasks;
using Windows.ApplicationModel.VoiceCommands;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Media.SpeechSynthesis;
using Windows.Security.Cryptography;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.System;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Documents;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using WordList;
using WordsOfLove;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
/*需要判断当前是否是复习模式？确认isReview属性
*（TODO）需要判断当前是什么用户？在OnNavigatedTo获得单词本id以及调用加载函数←这里还没写，暂时先不搞多用户
*需要加载单词本？在OnNavigatedTo获得单词本id以及调用加载函数
*如果用户点击了记不清的按钮？BtnForget_Click函数
*如果用户回答正确？在reciteCorect()里面处理
*如果用户回答完了一个学习周期需要进入复习模式？我在写了，先用Debug.writline（“学习周期结束”）顶着
*/
namespace App1
{
    /// <summary>
    /// 单词学习页面
    /// </summary>
    /// 
    public class vocUtils//单词学习工具类
    {
        static readonly HttpClient client = new HttpClient();
        Windows.Storage.StorageFolder temporaryFolder = ApplicationData.Current.TemporaryFolder;//获得UWP的临时目录
        public async Task<bool> DownloadFile(string url, string fileName,bool isWords=false,string words="")//下载文件到缓存文件夹
        {
            bool sign = true;
            try
            {
                Debug.WriteLine("start down");
                HttpResponseMessage response = await client.GetAsync(url);
                using (Stream stream = await response.Content.ReadAsStreamAsync())
                {
                    //获取文件后缀
                    //string extension = Path.GetExtension(response.RequestMessage.RequestUri.ToString());
                    Debug.WriteLine("making file");
                    StorageFile downloadFile = await temporaryFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
                    byte[] buffer = new byte[1024 * 1024];
                    int readLength = 0;
                    int length;
                    using (Stream f = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(fileName, CreationCollisionOption.OpenIfExists))
                    {
                        f.Seek(0, SeekOrigin.End);
                        await f.WriteAsync(buffer, 0, buffer.Length);
                    }
                    while ((length = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
                    {
                        IBuffer ibuffer = CryptographicBuffer.CreateFromByteArray(buffer);
                        Debug.WriteLine("Loading buffer");
                        readLength += length;
                        // 写入到文件
                        await FileIO.WriteBufferAsync(downloadFile, ibuffer);
                    }
                    Debug.WriteLine("FileDownloaded");
                    /* using (FileStream fileStream = new FileStream($"{directoryName}/{fileName}{extension}", FileMode.CreateNew))
                     {
                         byte[] buffer = new byte[1024*5];
                         int readLength = 0;
                         int length;
                         while ((length = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
                         {
                             readLength += length;
                             // 写入到文件
                             fileStream.Write(buffer, 0, length);
                         }
                     }*/
                }
            }
            catch (Exception E)
            {
                sign = false;
                Debug.WriteLine(E.Message);
                if (isWords)//if offline, read words by windows
                {
                    readWordOffline(words);
                }
            }
            return sign;
        }
        public async void readWordOffline(String words)//使用windows语音离线阅读
        {
            MediaElement mediaElement = new MediaElement();
            // The object for controlling the speech synthesis engine (voice).
            var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
            // Generate the audio stream from plain text.
            SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(words);
            // Send the stream to the media object.
            mediaElement.SetSource(stream, stream.ContentType);
            mediaElement.Play();
        }
        public async void playSound(string url,string fileName)//下载并播放url的音频
        {

            await DownloadFile(url, fileName);//先等待下载
            try
            {
                MediaElement vocSound = new MediaElement();
                StorageFile sampleFile = await temporaryFolder.GetFileAsync(fileName);
                //var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
                Debug.WriteLine(sampleFile.ContentType);
                Debug.WriteLine(sampleFile.DateCreated);
                //String timestamp = await FileIO.ReadTextAsync(sampleFile);
                // Debug.WriteLine(timestamp);
                vocSound.SetSource(await sampleFile.OpenAsync(FileAccessMode.Read), sampleFile.ContentType);
                vocSound.Play();
                //vocSound.SetSource(stream, sampleFile.ContentType);

                // vocSound.Play();
                Debug.WriteLine("Played");
                // Data is contained in timestamp
            }
            catch (Exception E)
            {
                Debug.WriteLine("Reading Err:" + E.Message);
                // Timestamp not found
            }
        }
    }
    public class absSentence//预览界面的句子格式
    {

        public absSentence(string en,string cn)
        {
            this.en = en;
            this.cn = cn;
        }
        public string en { get; set; }
        public string cn { get; set; }
    }
    public sealed partial class WordPage : Page
    {
        bool isReview=false;//当前是否是复习模式
        dicJson vocObj = new dicJson();//字典数据格式
        String currentWord = "apple";//The word to recite
        String currentInput = "";//word inputed
        VocUser user = new VocUser();//User who started reciting words
        vocUtils vu = new vocUtils();
        public double currentCorrentPercent { get; set; }
        int vocSize = 0;
        public ObservableCollection<absSentence> overviewSentences { get; } = new ObservableCollection<absSentence>();//右侧预览界面显示的句子
        public ObservableCollection<string> vocMeanings { get; } = new ObservableCollection<string>();//单词释义的列表

        public WordPage()
        {
            this.InitializeComponent();
            BtnGlance.AddHandler(PointerPressedEvent, new PointerEventHandler(BtnGlance_PointerPressed), true);//给瞄一眼按钮动态添加事件响应函数（只能这么添加）
            BtnGlance.AddHandler(PointerReleasedEvent,new PointerEventHandler(BtnGlance_PointerReleased), true);//给瞄一眼按钮动态添加事件响应函数（只能这么添加）
        }
        

        private void playVocabulary(object sender, RoutedEventArgs e)//播放语音
        {
            Load_Overview_Sentence("apple");
            if (((Button)sender).Name== "playVacUK")
            {
                Debug.WriteLine("playUk");
                vu.playSound($"http://dict.youdao.com/dictvoice?audio={currentWord}&type=1", "voc.wav");
            }
            else
            {
                Debug.WriteLine("playUs");
                vu.playSound($"http://dict.youdao.com/dictvoice?audio={currentWord}&type=2", "voc.wav");
            }
            return;
        }

        private void Word_KeyDown(object sender, KeyRoutedEventArgs e)//当用户进行输入进行判断
        {
           
            int input = (int)e.Key;
            if(input==8)//backspace
            {
                if (currentInput.Length > 0)
                {
                    currentInput = currentInput.Substring(0, currentInput.Length - 1);
                    updateCurrentVoc();
                }
                return;
            }
            if (input < 65 || input > 90)//not backSpace
            {
                return;
            }
            if (currentInput.Length >= vocSize)//max
            {
                return;
            }
            currentInput += (char)('a'+(input-65));
            updateCurrentVoc();
            if(currentInput==currentWord){//用户输入正确的单词
                reciteCorrect();//调用这个函数
            }
        }
        private void resetWord(String word)
        {
            reciteWord.Text = "";
        }
        private void Load_Overview_Sentence(String keyWord){//测试函数，用于加载右侧预览句子
            Debug.WriteLine("loading sen for:"+keyWord);
            overviewSentences.Add(new absSentence("aaa","bbb"));
            overviewSentences.Add(new absSentence("ccc", "ddd"));
            OverViewSenGridView.ItemsSource = overviewSentences;
            OverViewDiscusGridView.ItemsSource = overviewSentences;
        }
        private void updateCurrentVoc()//根据单词和用户输入更新输入栏
        {
            String currentState = "";
            for (int i = 0; i < currentInput.Length; i++)
            {
                currentState += currentInput[i];
                if (i != vocSize - 1)
                    currentState += " ";
            }
            for(int j= currentInput.Length; j < vocSize; j++)
            {
                currentState += "_";
                if (j != vocSize - 1)
                    currentState += " ";
            }
            reciteWord.Text = currentState;
            return;
        }
        private void iniVoc(string word)//重置单词输入
        {
            currentWord = word;
            vocSize = word.Length;
            string currentState = "";
            for(int i = 0; i < vocSize; i++)
            {
                currentState += "_";
                if(i!=vocSize-1)
                currentState += " ";
            }
            reciteWord.Text = currentState;

        }
        private async Task fetchNewVoc(string word)
        {
            using (var client = new HttpClient())
            {
                Debug.WriteLine("fetching datas");
                client.DefaultRequestHeaders.Add("user-agent", @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36");//添加HTTP头
                String vocJsonString = await client.GetStringAsync($"https://migu.plus/api/dic.php?word={word}").ConfigureAwait(false);
                vocObj = JsonConvert.DeserializeObject<dicJson>(vocJsonString);
                Debug.WriteLine(vocObj.word);
            }
        }
        private void iniNewVoc(string word)//加载新的单词
        {
           // iconNext.Text = "&#57633;";
            textNext.Text = "加载中";
            try { 
           fetchNewVoc(word).Wait();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
              //  iconNext.Text = "&#57748;";
                textNext.Text = "请重试";
                return;
            }
            reciteWord.Foreground = new SolidColorBrush(Colors.White);
            iniVoc(word);
            vocMeanings.Clear();
            if (vocObj.picDic.avali)//changeBg
            {
                changeBG(vocObj.picDic.url);
            }
            else
            {
                changeBG();
            }
            ukPhone.Text = $"英 [{vocObj.phone.uk}]";
            usPhone.Text = $"英 [{vocObj.phone.us}]";
            string examTypeStr = "";
            if (vocObj.exam_type.Count > 0)
            {
                for(int i=0;i< vocObj.exam_type.Count; i++)
                {
                    examTypeStr += $"{vocObj.exam_type[i]}; ";
                }
            }
            if (vocObj.trs.Count > 0)
            {
                for(int j = 0; j < vocObj.trs.Count; j++)
                {
                    vocMeanings.Add(vocObj.trs[j]);
                }
            }
            //iconNext.Text = "&#57641";
            textNext.Text = "记不清";
            examType.Text = examTypeStr;
        }
        private void BtnMark_Click(object sender, RoutedEventArgs e)//标记这个单词很重要，目前是调用测试函数用的
        {
            //iniVoc("apple");
            Debug.WriteLine("Start loading");
            UserService.CreateWordList(user);
            UserService.CreateWordList(user);
            List<Word> words = UserService.GetWordList(user);
            if (user.List.Count == 0) Debug.WriteLine("a");
            else if (words.Count == 0) Debug.WriteLine("b");
            else
            {
                foreach (Word wd in words)
                {
                    Debug.WriteLine(wd.Id + " " + wd.Text + " " + wd.Proficiency + " " + wd.Times); ;
                }
            }
        }


        private void changeBG(string uri= "https://i.loli.net/2020/11/08/mFV5wlvdHLAIpN9.png")//Change BackGround
        {
            this.Background = new ImageBrush { ImageSource = new BitmapImage(new Uri(uri)), Stretch = Stretch.UniformToFill };
        }


        private void BtnGlance_PointerPressed(object sender, PointerRoutedEventArgs e)//按下瞄一眼显示原词并且重置输入
        {
            Debug.WriteLine("press");
            reciteWord.Text = currentWord;
            currentInput = "";
            return;
        }

        private void BtnGlance_PointerReleased(object sender, PointerRoutedEventArgs e)//松开瞄一眼就恢复答题页面
        {
            Debug.WriteLine("release");
            iniVoc(currentWord);
        }

        private async void BtnEasy_Click(object sender, RoutedEventArgs e)//太简单的按钮
        {
            Debug.WriteLine("loadNextWord");
            iniNewVoc("account");
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)//页面跳转过来的时候调用的函数
        {
            if (e.Parameter.GetType().Equals(typeof(vocBook)))//在这里获得单词书编号，开始加载wordList
            {
                vocBook currentBook = (vocBook)e.Parameter;
                vocBookTitle.Text = currentBook.bookName;
                Debug.WriteLine(currentBook.bookName);
            }
            else
            {
                Debug.WriteLine("Navigated to Voc page without vocBook Para, please check the invoke funcs");
            }

        }

        private void BtnForget_Click(object sender, RoutedEventArgs e)//用户点击了记不清，传递信息然后加载下一个单词
        {

        }
        private void reciteCorrect(){//回答正确，传递信息然后加载下一个单词
            reciteWord.Foreground = new SolidColorBrush(Colors.DarkOliveGreen);
            //Debug.WriteLine($"Wow,you correctly recited: {currentword}");
        }
    }
}
